package test.cz.cvut.fit.web.nakupniSeznam.ws;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;

import test.cz.cvut.fit.web.nakupniSeznam.Constants;

import com.google.gson.Gson;

import cz.cvut.fit.web.nakupniSeznam.dao.UserDAO;
import cz.cvut.fit.web.nakupniSeznam.data.User;

public class Utils {
	
	public static String getJSONString(HttpRequestBase request) {
		// initialize
				InputStream is = null;
				HttpResponse response = null;

				// http request send
				try {
					HttpClient httpclient = new DefaultHttpClient();
					response = httpclient.execute(request);
					HttpEntity entity = response.getEntity();
					is = entity.getContent();

				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}

				// convert response to string
				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(
							is, Constants.WS_CHARSET), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					return sb.toString();
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
	}

	public static User postUser() {
		String json = "";
		HttpPost post = new HttpPost(Constants.WS_URL + "user");
		json = Utils.getJSONString(post);
		Gson gson = new Gson();
		User user = gson.fromJson(json, User.class);
		User userFromDb = UserDAO.getInstance().getByKey(user.getKey());
		return userFromDb;
	}
}